"""
活动记录工具类
用于记录用户操作活动和登录日志
"""
from datetime import datetime
from typing import Optional, Dict, Any
from motor.motor_asyncio import AsyncIOMotorDatabase
from bson import ObjectId
import logging

logger = logging.getLogger(__name__)

class ActivityLogger:
    """活动记录器"""
    
    @staticmethod
    async def log_activity(
        db: AsyncIOMotorDatabase,
        user_id: str,
        action: str,
        target_type: str,
        target_id: str,
        target_name: str,
        description: str,
        ip_address: Optional[str] = None,
        user_agent: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> bool:
        """
        记录用户活动
        
        Args:
            db: 数据库连接
            user_id: 用户ID
            action: 操作类型 (create, update, delete, view, login, logout等)
            target_type: 目标类型 (user, project, task, defect等)
            target_id: 目标ID
            target_name: 目标名称
            description: 操作描述
            ip_address: IP地址
            user_agent: 用户代理
            metadata: 额外元数据
            
        Returns:
            bool: 是否记录成功
        """
        try:
            activity_data = {
                "user_id": user_id,
                "action": action,
                "target_type": target_type,
                "target_id": target_id,
                "target_name": target_name,
                "description": description,
                "ip_address": ip_address,
                "user_agent": user_agent,
                "metadata": metadata or {},
                "created_at": datetime.utcnow()
            }
            
            await db.activity_logs.insert_one(activity_data)
            return True
            
        except Exception as e:
            logger.error(f"Failed to log activity: {str(e)}")
            return False
    
    @staticmethod
    async def log_login(
        db: AsyncIOMotorDatabase,
        user_id: str,
        ip_address: str,
        user_agent: str,
        device_info: Optional[str] = None,
        success: bool = True
    ) -> bool:
        """
        记录登录日志
        
        Args:
            db: 数据库连接
            user_id: 用户ID
            ip_address: IP地址
            user_agent: 用户代理
            device_info: 设备信息
            success: 登录是否成功
            
        Returns:
            bool: 是否记录成功
        """
        try:
            login_data = {
                "user_id": user_id,
                "ip_address": ip_address,
                "user_agent": user_agent,
                "device_info": device_info,
                "success": success,
                "login_time": datetime.utcnow()
            }
            
            await db.login_logs.insert_one(login_data)
            return True
            
        except Exception as e:
            logger.error(f"Failed to log login: {str(e)}")
            return False
    
    @staticmethod
    async def log_user_action(
        db: AsyncIOMotorDatabase,
        user_id: str,
        action: str,
        description: str,
        ip_address: Optional[str] = None,
        user_agent: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> bool:
        """
        记录用户相关操作
        
        Args:
            db: 数据库连接
            user_id: 用户ID
            action: 操作类型
            description: 操作描述
            ip_address: IP地址
            user_agent: 用户代理
            metadata: 额外元数据
            
        Returns:
            bool: 是否记录成功
        """
        return await ActivityLogger.log_activity(
            db=db,
            user_id=user_id,
            action=action,
            target_type="user",
            target_id=user_id,
            target_name="用户资料",
            description=description,
            ip_address=ip_address,
            user_agent=user_agent,
            metadata=metadata
        )
    
    @staticmethod
    async def log_project_action(
        db: AsyncIOMotorDatabase,
        user_id: str,
        project_id: str,
        project_name: str,
        action: str,
        description: str,
        ip_address: Optional[str] = None,
        user_agent: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> bool:
        """
        记录项目相关操作
        
        Args:
            db: 数据库连接
            user_id: 用户ID
            project_id: 项目ID
            project_name: 项目名称
            action: 操作类型
            description: 操作描述
            ip_address: IP地址
            user_agent: 用户代理
            metadata: 额外元数据
            
        Returns:
            bool: 是否记录成功
        """
        return await ActivityLogger.log_activity(
            db=db,
            user_id=user_id,
            action=action,
            target_type="project",
            target_id=project_id,
            target_name=project_name,
            description=description,
            ip_address=ip_address,
            user_agent=user_agent,
            metadata=metadata
        )
    
    @staticmethod
    async def log_task_action(
        db: AsyncIOMotorDatabase,
        user_id: str,
        task_id: str,
        task_title: str,
        action: str,
        description: str,
        ip_address: Optional[str] = None,
        user_agent: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> bool:
        """
        记录任务相关操作
        
        Args:
            db: 数据库连接
            user_id: 用户ID
            task_id: 任务ID
            task_title: 任务标题
            action: 操作类型
            description: 操作描述
            ip_address: IP地址
            user_agent: 用户代理
            metadata: 额外元数据
            
        Returns:
            bool: 是否记录成功
        """
        return await ActivityLogger.log_activity(
            db=db,
            user_id=user_id,
            action=action,
            target_type="task",
            target_id=task_id,
            target_name=task_title,
            description=description,
            ip_address=ip_address,
            user_agent=user_agent,
            metadata=metadata
        )

# 常用操作类型常量
class ActionTypes:
    # 用户操作
    USER_LOGIN = "login"
    USER_LOGOUT = "logout"
    USER_REGISTER = "register"
    USER_UPDATE_PROFILE = "update_profile"
    USER_CHANGE_PASSWORD = "change_password"
    USER_UPLOAD_AVATAR = "upload_avatar"
    USER_UPDATE_SETTINGS = "user_update_settings"
    USER_UPDATE_NOTIFICATION = "update_notification"
    
    # 项目操作
    PROJECT_CREATE = "create"
    PROJECT_UPDATE = "update"
    PROJECT_DELETE = "delete"
    PROJECT_VIEW = "view"
    PROJECT_JOIN = "join"
    PROJECT_LEAVE = "leave"
    
    # 任务操作
    TASK_CREATE = "create"
    TASK_UPDATE = "update"
    TASK_DELETE = "delete"
    TASK_ASSIGN = "assign"
    TASK_COMPLETE = "complete"
    TASK_COMMENT = "comment"
    
    # 缺陷操作
    DEFECT_CREATE = "create"
    DEFECT_UPDATE = "update"
    DEFECT_DELETE = "delete"
    DEFECT_ASSIGN = "assign"
    DEFECT_RESOLVE = "resolve"
    DEFECT_CLOSE = "close"

# 目标类型常量
class TargetTypes:
    USER = "user"
    PROJECT = "project"
    TASK = "task"
    DEFECT = "defect"
    NOTIFICATION = "notification"
    SYSTEM = "system"